#include "CaptionTips.h"
#include <QPainter>
#include <QDebug>
#include <QFontMetrics>



CaptionTips::CaptionTips( QWidget* parent):
    _index(0),
    _width(1),
    _iInterval(20)
{
    connect(_timer_updateContext = new QTimer(this), &QTimer::timeout, [=](){
        update();
        _index += _iSpeed;
        if( _index*_width >( fontMetrics().width(_strContextList.first())) + width())
        {
            NextContext();
        }
    });
}

void CaptionTips::AppendContext(QString strContext, int iSpeed)
{
    _strContextList.append(strContext);
    _iSpeed = iSpeed;
    PlayContext();
}

void CaptionTips::PlayContext()
{
    if(_timer_updateContext->isActive() == false )
    {
        _timer_updateContext->start(_iInterval);
    }
}

void CaptionTips::NextContext()
{
    _timer_updateContext->stop();
    clear();
    _strContextList.removeFirst();
    _index = 0;
    if( false == _strContextList.isEmpty() )
    {
        PlayContext();
    }
    else
    {
        StopContext();
    }
}

void CaptionTips::StopContext()
{
    if( _timer_updateContext->isActive() == true)
    {
        _timer_updateContext->stop();
    }
    clear();
    _strContextList.clear();
    _index = 0;
}

void CaptionTips::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    if( _strContextList.isEmpty() == false)
    {
        painter.drawText (width()- _width*_index, 22, _strContextList.first().left(_index));
    }
    //painter.drawText( 0-_width*_index, 22, _strContext);
}

CaptionTips::~CaptionTips()
{

}
